﻿@page "/"
@inject NavigationManager Nav
@inject eShop.HybridApp.Services.CatalogService CatalogService

<PageTitle>AdventureWorks</PageTitle>
<SectionContent SectionName="page-header-title">Ready for a new adventure?</SectionContent>
<SectionContent SectionName="page-header-subtitle">Start the season with the latest in clothing and equipment.</SectionContent>

<div class="catalog">
    <eShop.HybridApp.Components.Pages.Catalog.CatalogSearch BrandId="@BrandId" ItemTypeId="@ItemTypeId" />

    @if (catalogResult is null)
    {
        <p>Loading...</p>
    }
    else
    {
        <div>
            <div class="catalog-items">
                @foreach (var item in catalogResult.Data)
                {
                    <CatalogListItem Item="@item" />
                }
            </div>

            <div class="page-links">
                @foreach (var pageIndex in GetVisiblePageIndexes(catalogResult))
                {
                    <NavLink ActiveClass="active-page" Match="@NavLinkMatch.All" href="@Nav.GetUriWithQueryParameter("page", pageIndex == 1 ? null : pageIndex)">@pageIndex</NavLink>
                }
            </div>
        </div>
    }
</div>

@code {
    const int PageSize = 9;

    [SupplyParameterFromQuery]
    public int? Page { get; set; }

    [SupplyParameterFromQuery(Name = "brand")]
    public int? BrandId { get; set; }

    [SupplyParameterFromQuery(Name = "type")]
    public int? ItemTypeId { get; set; }

    CatalogResult? catalogResult;

    static IEnumerable<int> GetVisiblePageIndexes(CatalogResult result)
        => Enumerable.Range(1, (int)Math.Ceiling(1.0 * result.Count / PageSize));

    protected override async Task OnParametersSetAsync()
    {
        catalogResult = await CatalogService.GetCatalogItems(
            Page.GetValueOrDefault(1) - 1,
            PageSize,
            BrandId,
            ItemTypeId);
    }
}
